"""用户管理API视图"""
from flask import request
from flask.views import MethodView
from flask_smorest import Blueprint
from flask_jwt_extended import jwt_required, get_jwt_identity
from flask_babel import gettext as _
from sqlalchemy import or_, func

from app.extensions import db
from app.models import User
from app.schemas.user import (
    UserSchema, 
    UserCreateSchema, 
    UserUpdateSchema, 
    UserQuerySchema
)
from app.responses import success_response, paginated_response
from app.status_codes import StatusCode, HttpStatusCode
from app.exceptions import (
    UserNotFoundException,
    UserAlreadyExistsException,
    AuthorizationException,
    ValidationException
)
from app.logs import logger

# 创建用户管理蓝图
users_bp = Blueprint(
    'users',
    __name__,
    url_prefix='/users',
    description='用户管理相关API'
)


@users_bp.route('/')
class UsersView(MethodView):
    """用户列表视图"""
    
    @jwt_required()
    @users_bp.arguments(UserQuerySchema, location="query")
    @users_bp.response(200, UserSchema(many=True))
    @users_bp.doc(
        summary="获取用户列表",
        description="分页获取用户列表，支持搜索和筛选"
    )
    def get(self, query_args):
        """获取用户列表"""
        
        # 获取当前用户
        current_user_id = get_jwt_identity()
        current_user = User.query.get(current_user_id)
        
        # 检查权限（只有管理员可以查看所有用户）
        if not current_user or not current_user.is_admin:
            raise AuthorizationException(_("无权限访问用户列表"))
        
        # 构建查询
        query = User.query
        
        # 搜索条件
        if query_args.get('search'):
            search_term = f"%{query_args['search']}%"
            query = query.filter(
                or_(
                    User.username.ilike(search_term),
                    User.email.ilike(search_term),
                    User.first_name.ilike(search_term),
                    User.last_name.ilike(search_term)
                )
            )
        
        # 激活状态筛选
        if query_args.get('is_active') is not None:
            query = query.filter(User.is_active == query_args['is_active'])
        
        # 排序
        sort_field = query_args.get('sort', 'created_at')
        order = query_args.get('order', 'desc')
        
        if hasattr(User, sort_field):
            sort_column = getattr(User, sort_field)
            if order == 'desc':
                query = query.order_by(sort_column.desc())
            else:
                query = query.order_by(sort_column.asc())
        
        # 分页
        page = query_args.get('page', 1)
        per_page = query_args.get('per_page', 10)
        
        pagination = query.paginate(
            page=page,
            per_page=per_page,
            error_out=False
        )
        
        users_data = [UserSchema().dump(user) for user in pagination.items]
        
        logger.info(f"管理员获取用户列表: 当前用户ID={current_user_id}, 页码={page}, 总数={pagination.total}")
        
        return paginated_response(
            data=users_data,
            page=page,
            per_page=per_page,
            total=pagination.total,
            message=_("获取用户列表成功")
        )
    
    @jwt_required()
    @users_bp.arguments(UserCreateSchema)
    @users_bp.response(201, UserSchema)
    @users_bp.doc(
        summary="创建用户",
        description="管理员创建新用户"
    )
    def post(self, user_data):
        """创建用户"""
        
        # 获取当前用户
        current_user_id = get_jwt_identity()
        current_user = User.query.get(current_user_id)
        
        # 检查权限（只有管理员可以创建用户）
        if not current_user or not current_user.is_admin:
            raise AuthorizationException(_("无权限创建用户"))
        
        # 检查用户名是否已存在
        if User.query.filter_by(username=user_data['username']).first():
            raise UserAlreadyExistsException(_("用户名已存在"))
        
        # 检查邮箱是否已存在
        if User.query.filter_by(email=user_data['email']).first():
            raise UserAlreadyExistsException(_("邮箱已被注册"))
        
        # 创建新用户
        user = User(
            username=user_data['username'],
            email=user_data['email'],
            first_name=user_data.get('first_name'),
            last_name=user_data.get('last_name'),
            avatar_url=user_data.get('avatar_url')
        )
        user.password = user_data['password']
        
        try:
            db.session.add(user)
            db.session.commit()
            
            logger.info(f"管理员创建用户成功: 管理员ID={current_user_id}, 新用户ID={user.id}")
            
            return success_response(
                data=UserSchema().dump(user),
                message=_("创建用户成功"),
                http_status=HttpStatusCode.CREATED
            )
            
        except Exception as e:
            db.session.rollback()
            logger.error(f"创建用户失败: {str(e)}")
            raise


@users_bp.route('/<int:user_id>')
class UserDetailView(MethodView):
    """用户详情视图"""
    
    @jwt_required()
    @users_bp.response(200, UserSchema)
    @users_bp.doc(
        summary="获取用户详情",
        description="根据用户ID获取用户详细信息"
    )
    def get(self, user_id):
        """获取用户详情"""
        
        # 获取当前用户
        current_user_id = get_jwt_identity()
        current_user = User.query.get(current_user_id)
        
        # 检查权限（管理员可以查看所有用户，普通用户只能查看自己）
        if not current_user:
            raise AuthorizationException(_("未找到当前用户"))
        
        if not current_user.is_admin and current_user_id != user_id:
            raise AuthorizationException(_("无权限查看其他用户信息"))
        
        # 获取目标用户
        user = User.query.get(user_id)
        if not user:
            raise UserNotFoundException(_("用户不存在"))
        
        logger.info(f"获取用户详情: 当前用户ID={current_user_id}, 目标用户ID={user_id}")
        
        return success_response(
            data=UserSchema().dump(user),
            message=_("获取用户详情成功")
        )
    
    @jwt_required()
    @users_bp.arguments(UserUpdateSchema)
    @users_bp.response(200, UserSchema)
    @users_bp.doc(
        summary="更新用户信息",
        description="更新指定用户的信息"
    )
    def put(self, user_data, user_id):
        """更新用户信息"""
        
        # 获取当前用户
        current_user_id = get_jwt_identity()
        current_user = User.query.get(current_user_id)
        
        # 检查权限（管理员可以更新所有用户，普通用户只能更新自己）
        if not current_user:
            raise AuthorizationException(_("未找到当前用户"))
        
        if not current_user.is_admin and current_user_id != user_id:
            raise AuthorizationException(_("无权限修改其他用户信息"))
        
        # 获取目标用户
        user = User.query.get(user_id)
        if not user:
            raise UserNotFoundException(_("用户不存在"))
        
        # 检查邮箱是否重复（排除自己）
        if 'email' in user_data:
            existing_user = User.query.filter(
                User.email == user_data['email'],
                User.id != user_id
            ).first()
            if existing_user:
                raise UserAlreadyExistsException(_("邮箱已被其他用户使用"))
        
        # 更新用户信息
        for field, value in user_data.items():
            if hasattr(user, field):
                setattr(user, field, value)
        
        try:
            db.session.commit()
            
            logger.info(f"更新用户信息成功: 当前用户ID={current_user_id}, 目标用户ID={user_id}")
            
            return success_response(
                data=UserSchema().dump(user),
                message=_("更新用户信息成功")
            )
            
        except Exception as e:
            db.session.rollback()
            logger.error(f"更新用户信息失败: {str(e)}")
            raise
    
    @jwt_required()
    @users_bp.response(204)
    @users_bp.doc(
        summary="删除用户",
        description="删除指定用户（管理员权限）"
    )
    def delete(self, user_id):
        """删除用户"""
        
        # 获取当前用户
        current_user_id = get_jwt_identity()
        current_user = User.query.get(current_user_id)
        
        # 检查权限（只有管理员可以删除用户）
        if not current_user or not current_user.is_admin:
            raise AuthorizationException(_("无权限删除用户"))
        
        # 不能删除自己
        if current_user_id == user_id:
            raise ValidationException(_("不能删除自己的账户"))
        
        # 获取目标用户
        user = User.query.get(user_id)
        if not user:
            raise UserNotFoundException(_("用户不存在"))
        
        try:
            db.session.delete(user)
            db.session.commit()
            
            logger.info(f"删除用户成功: 管理员ID={current_user_id}, 被删除用户ID={user_id}")
            
            return success_response(
                message=_("删除用户成功"),
                http_status=HttpStatusCode.NO_CONTENT
            )
            
        except Exception as e:
            db.session.rollback()
            logger.error(f"删除用户失败: {str(e)}")
            raise


@users_bp.route('/<int:user_id>/toggle-status')
class UserToggleStatusView(MethodView):
    """用户状态切换视图"""
    
    @jwt_required()
    @users_bp.response(200, UserSchema)
    @users_bp.doc(
        summary="切换用户状态",
        description="启用或禁用用户账户（管理员权限）"
    )
    def post(self, user_id):
        """切换用户激活状态"""
        
        # 获取当前用户
        current_user_id = get_jwt_identity()
        current_user = User.query.get(current_user_id)
        
        # 检查权限（只有管理员可以切换用户状态）
        if not current_user or not current_user.is_admin:
            raise AuthorizationException(_("无权限修改用户状态"))
        
        # 不能修改自己的状态
        if current_user_id == user_id:
            raise ValidationException(_("不能修改自己的账户状态"))
        
        # 获取目标用户
        user = User.query.get(user_id)
        if not user:
            raise UserNotFoundException(_("用户不存在"))
        
        # 切换状态
        user.is_active = not user.is_active
        
        try:
            db.session.commit()
            
            status_text = "启用" if user.is_active else "禁用"
            logger.info(f"{status_text}用户成功: 管理员ID={current_user_id}, 目标用户ID={user_id}")
            
            return success_response(
                data=UserSchema().dump(user),
                message=_(f"用户已{status_text}")
            )
            
        except Exception as e:
            db.session.rollback()
            logger.error(f"切换用户状态失败: {str(e)}")
            raise 